package weather.language.extractor;

import java.util.*;

import weather.language.forecast.*;

public class WeatherKeywordExtractor
{
	public void extract(String sentence)
	{
		Map<String, WeatherGroup> varToWheatherGroup = new HashMap<String, WeatherGroup>();
		Map<String, String> varToUsedWheaterKeyword = new HashMap<String, String>();
		
		StringBuffer sentenceWithVars = new StringBuffer(sentence);
		
		int varNum = 0;
		int i;
		
		boolean siteExtracted;
		do
		{
			siteExtracted = false;
			for (String siteName: keywordsToGroupsMap.keySet())
				while ((i = new String(sentenceWithVars).toLowerCase().indexOf(
						siteName.toLowerCase())) != -1)
				{	
					siteExtracted = true;
					
					String var = "$(wkey_" + varNum++ + ")";
					sentenceWithVars = sentenceWithVars.replace(i, i + siteName.length(), var);
					varToWheatherGroup.put(var, keywordsToGroupsMap.get(siteName));
					varToUsedWheaterKeyword.put(var, siteName);
				}
		}
		while (siteExtracted);
		
		this.sentenceWithVars = new String(sentenceWithVars);
		this.varToWheatherGroup = varToWheatherGroup;
		this.varToUsedWheaterKeyword = varToUsedWheaterKeyword;
	}
	
	public String getSentenceWithVars()
	{
		return sentenceWithVars;
	}

	public Map<String, WeatherGroup> getVarToWheatherGroup()
	{
		return varToWheatherGroup;
	}

	public Map<String, String> getVarToUsedWheaterKeyword()
	{
		return varToUsedWheaterKeyword;
	}
	
	public void loadWeatherGroupsSet(Set<WeatherGroup> whetherGroups)
	{
		keywordsToGroupsMap.clear();
		for (WeatherGroup wg: whetherGroups)
		{
			this.weatherGroups.add(wg);
			for (String name: wg.getKeywords())
				keywordsToGroupsMap.put(name, wg);
		}
	}
	
	private String sentenceWithVars;
	private Map<String, WeatherGroup> varToWheatherGroup;
	private Map<String, String> varToUsedWheaterKeyword;

	private Map<String, WeatherGroup> keywordsToGroupsMap = new TreeMap<String, WeatherGroup>(new StringLengthComparator());
	private Set<WeatherGroup> weatherGroups = new HashSet<WeatherGroup>();
	
	private static class StringLengthComparator implements Comparator<String>
	{
		@Override
		public int compare(String s1, String s2)
		{
			int lendiff = s1.length() - s2.length();
			
			if (lendiff < 0)
				return 1;
			else if (lendiff > 0)
				return -1;
			else
				return s1.compareTo(s2);
		}
	}
}
